const express = require("express");
// 跨域
const cors = require("cors");
// 表单验证规则
const joi = require("joi");
// 解析token
const expressJwt = require("express-jwt");
// 加密配置
const config = require("./src/utils/config");
// 全局别名
require("module-alias/register");
const server = express();

const userRouter = require("@/router/user");
const loginRouter = require("@/router/login");
const employeeRouter = require("@/router/employee");
const departmentRouter = require("@/router/department");
const recruitmentplan = require("@/router/recruitmentplan");

// 捕获错误中间件
const catchError = (err, req, res, next) => {
  // 验证失败
  if (err instanceof joi.ValidationError) return res.err(err);
  //   身份认证失败
  if (err.name === "UnauthorizedError") return res.err("身份认证失败");
  next();
};

// res.send()函数封装
const toSend = (req, res, next) => {
  res.ok = (data = null, msg = "", code = 0) => {
    res.send({
      code,
      data,
      msg,
    });
  };
  res.err = (err, code = 500) => {
    res.send({
      code,
      msg: err instanceof Error ? err.message : err,
    });
  };
  next();
};

// 中间件使用
server.use(cors());
server.use(toSend);

// 解析 x-www-form-urlencoded
server.use(express.urlencoded({ extended: false }));
server.use(express.json());

// 解析token字符串
server.use(
  expressJwt
    .expressjwt({ secret: config.key, algorithms: ["HS256"] })
    .unless({
      path: [/^\/login\//],
    })
);

// 使用路由模块
server.use("/login", loginRouter);
server.use("/user", userRouter);
server.use("/employee", employeeRouter);
server.use("/department", departmentRouter);
server.use("/recruitmentplan", recruitmentplan);

// 使用捕获错误中间件
server.use(catchError);

server.listen(8080, () => {
  console.log("http://localhost:8080 启动!");
});
// server.listen(3000, () => {
//   console.log("http://localhost:3000 启动!");
// });